package com.jhx.mall.dao;

import java.sql.*;

/**
 * 数据库操作工具类
 * @version v1.0
 * @Author 郴州科泰
 * @Create 2024-07-14 - 11:38
 */
public class BaseDao {

    protected Connection conn;  // 连接对象
    protected PreparedStatement pstmt;  // 执行对象
    protected ResultSet rs;  // 结果集对象

    public Connection getConnection() {
        try {
            // 1、加载驱动   ctrl + alt + t
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2、获取数据库连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dts_shop?serverTimezone=GMT-8&characterEncoding=utf8", "root", "root");
            // Context ctx = new InitialContext();
            // DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/ktmall");
            // conn = ds.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    // 释放资源
    public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
        try {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行增删改的SQL语句
     * @param sql 预编译的SQL语句。  带?点位符
     * @param params 参数数组
     * @return 返回受影响的行数
     */
    public int executeUpdate(String sql, Object ... params) {
        conn = getConnection();
        int count = 0;  // 用来保存受影响的行数
        try {
            pstmt = conn.prepareStatement(sql);  // 创建执行对象
            // 为预编译的SQL语句赋值，即替换掉?占位符
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            count = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            closeAll(rs, pstmt, conn);
        }
        return count;
    }

    /**
     * 执行查询的SQL语句
     * @param sql 预编译的SQL语句
     * @param params 参数数组
     * @return 返回结果集ResultSet对象
     */
    public ResultSet executeQuery(String sql, Object ... params) {
        conn = getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 是不需要关闭连接
        return rs;
    }
}
